// pages/takesTwo/takesTwo.js
const app = getApp();
let tool = require('../../utils/tool.js');
Page({
  data: {
    innerAudioContext: new Object(),
    gameSecond: 50, //过关时间
    gameSecond2: 0,
    maskDis: 'flex',
    jbDis: 'flex',
    ggDis: 'none',
    gfDis: 'none',
    passNum: '0',
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    wrongWorlds: [],
    curworng: -1,
    worldsEn: '',
    worldsCh: '',
    rightNum: 6,
    curentChoice: {
      'en': -1,
      'ch': -1
    },
    rightArr: new Array(),
    timer: '',
    allword: [],
    errword: [],
    curentIdx: false,
    clickArr: [],
	timerdata:[],
    reviewTime: 0,
    replayFlag: false,
    date: '', //学习日期
	reply:false,
  },
  onLoad: function(options) {
    var that = this;
    //获取传过来的日期
    that.setData({
      date: options.date,
    })
    console.log(that.data.date)
    this.data.innerAudioContext = wx.createInnerAudioContext()
    this.data.innerAudioContext.autoplay = false;
    this.data.innerAudioContext.loop = false;
    this.data.innerAudioContext.src = app.globalData.mp3.selected;
  },
  onReady: function() {},
  onShow: function() {},
  onHide: function() {},
  onUnload: function() {},

  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  playmp3: function(mp3url) { //播放音效

    this.data.innerAudioContext.src = mp3url;
    this.data.innerAudioContext.play();

  },
  setSec: function(e) { //设置描述
    if (!this.data.replayFlag) {
      this.setData({
        maskDis: 'none',
        jbDis: 'none',
        gameSecond2: e.currentTarget.dataset.passsce,
        gameSecond: e.currentTarget.dataset.passsce
      });
      this.nextPass();
    } else {
      this.setData({
        maskDis: 'none',
        jbDis: 'none',
        gameSecond2: e.currentTarget.dataset.passsce,
        gameSecond: e.currentTarget.dataset.passsce,
      })
      this.rePass();
    }
	if(this.data.reply){
		this.setData({
			wrongWorlds: [],
			curworng: -1,
			rightNum: 6,
			curentChoice: {
			  'en': -1,
			  'ch': -1
			},
			rightArr: new Array(),
			timer: '',
			// allword: [],
			// errword: [],
			curentIdx: false,
			clickArr: [],
			reviewTime: 0,
			replayFlag: false
		})
	}

  },
  choiceOption: function(e) { //选择选项
    this.setData({
      curworng: -1
    });
    let btype = e.currentTarget.dataset.type;
    let key = e.currentTarget.dataset.yindex;

    if (btype == 'en') {
      this.playmp3(app.globalData.mp3.selected);
      this.data.curentIdx = e.currentTarget.dataset.idx;
      this.setData({
        curentChoice: {
          'en': key,
          'ch': "-1"
        }
      })
    }
    if (btype == 'ch') {
      if (this.data.curentChoice.en == '-1') { //没有选中英文无任何操作
        return;
      }
      if (this.data.curentChoice.en == key) { //选对了
        //记录被点击过的英文
        if (this.data.clickArr.indexOf(this.data.curentIdx) == -1) {
          this.data.clickArr.push(this.data.curentIdx);
        }
        this.playmp3(app.globalData.mp3.doright);
        let temparr = this.data.rightArr;
        if (temparr.indexOf(key) == -1) {
          temparr.push(key)
        }
        this.setData({
          rightArr: temparr,
          curentChoice: this.data.curentChoice,
          curentChoice: {
            'en': "-1",
            'ch': "-1"
          }
        });
        if (this.data.rightArr.length == 6 && this.data.wrongWorlds.length >= 3) {
          this.data.replayFlag = true;
          this.setData({
            gfDis: 'flex',
            maskDis: 'flex'
          });
        } else if (this.data.rightArr.length == 6 && this.data.wrongWorlds.length < 3) {

          this.setData({
            ggDis: 'flex',
            maskDis: 'flex'
          });
        }
      } else {
        //选错了
        app.vibrateShortTap();
        let temparr = this.data.wrongWorlds;
        this.playmp3(app.globalData.mp3.selectwrong)
        if (temparr.indexOf(key) == -1) {
          temparr.push(key);
        }
        if (this.data.errword.indexOf(this.data.worldsEn[this.data.curentIdx]['id']) == -1) {
          this.data.errword.push(this.data.worldsEn[this.data.curentIdx]['id']);
        }

        this.setData({
          wrongWorlds: temparr,
          curworng: key
        })
      }
    }
  },
  daojishi: function() { //倒计时
    let that = this;
    that.data.timer = setInterval(function() {
      app.globalData.taskTwoMinuts = app.globalData.taskTwoMinuts + 1;
      let num = parseInt(that.data.gameSecond) - 1
      if (num < 10 && num >= 0) {
        num = "0" + num.toString();
      }
      that.setData({
        gameSecond: num
      });

      if (parseInt(that.data.gameSecond) <= 0) {
        // clearInterval(that.data.timer);
		that.cleartime();
        /** if (that.data.rightArr.length >6 && that.data.wrongWorlds.length >= 3) {
       
           that.setData({
             gfDis: 'flex',
             maskDis: 'flex',
             replayFlag:true
           });
         } //else if (that.data.rightArr.length == 6 && that.data.wrongWorlds.length < 3) {
         else**/
        if (that.data.rightArr.length > 3) {
          that.setData({
            ggDis: 'flex',
            maskDis: 'flex'
          });
        } else {

          that.setData({
            gfDis: 'flex',
            maskDis: 'flex',
            replayFlag: true
          });
        }
      }
    }, 1000);
	that.data.timerdata.push(that.data.timer)
  },
  cleartime(){
	  for (var i = 0; i < this.data.timerdata.length; i++) {
		clearInterval(this.data.timerdata[i]);
	  }
  },
  nextPass: function() { //进入下一关
    if (this.data.passNum > 0) {
      this.collectWrong();
    }
    this.setData({
      gameSecond: this.data.gameSecond2,
      maskDis: 'none',
      ggDis: 'none',
      gfDis: 'none'
    });
    // clearInterval(this.data.timer);
	this.cleartime();
    this.initDdata();
    let datas = this.getData();
    let that = this;
    datas.then(function(rs) {
    if (rs.data.code == 10001) {
        wx.redirectTo({
          url: '/pages/login/login',
        })
        return;
      }

      if (rs.code !== 1) {
        wx.showToast({
          title: rs.info,
          icon: 'none',
          duration: 2000
        })
        let timerName = setTimeout(function() {
          wx.navigateBack({
            delta: -1
          })
          // wx.switchTab({
          //   url: '../review/review',
          // })
        }, 1500)
        return;
      }
      if (rs.data.word.length<1 || rs.data.word[0].length < 5) {
        that.toReport();
        return;
      };
   
  
      that.data.passNum = parseInt(that.data.passNum) + 1; //过关数
      that.setData({
        worldsEn: rs.data.word[0],
        worldsCh: rs.data.word[1],
        passNum: that.data.passNum
      })
    })
    if (this.data.gameSecond2 > 0) {
      this.daojishi();
    }

  },
  getData: function() { //读取接口数据
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token,
      page: parseInt(that.data.passNum) + 1,
      date: app.globalData.studyDate
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "review/pop?sign=" + sign;
    let takesPro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );

    let datas = false;
    datas = takesPro.then(function(rs) {
      wx.hideLoading();
      return rs.data;

    });
    return datas;

  },
  initDdata: function() { //过关初始化数据
    this.setData({
      wrongWorlds: [],
      curworng: -1,
      worldsEn: '',
      worldsCh: '',
      rightNum: 6,
      curentChoice: {
        'en': -1,
        'ch': -1
      },
      rightArr: new Array(),
      clickArr: new Array()
    })
  },
  toReport: function() { //跳转到报告页面
    this.collectWrong();
    let upResult = this.upResult();
    upResult.then(function(res) {
      if (res.data.code == 1) {
        app.globalData.taskTwoUpresult = res.data.data;
        wx.redirectTo({
          url: './twoReprot/twoReprot'
        })
      } else {
        wx.showToast({
          title: res.data.info,
          icon: 'none',
          duration: '2000'
        })
      }
    });

  },
  upResult: function() { //提交结果
    let that = this;
    let paramArr = {
      type: 1,
      allword: this.data.allword.join(','),
      errword: this.data.errword.join(','),
      access_token: app.globalData.studentInfo.access_token,
      date: that.data.date
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "review/upresult?sign=" + sign;
    let takesPro = new Promise(
      function(resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );
    return takesPro;
  },
  collectWrong: function() { //清算本关错误单词
    for (let idx in this.data.worldsEn) {
      if (this.data.clickArr.indexOf(parseInt(idx)) == -1) {
        if (this.data.errword.indexOf(this.data.worldsEn[idx].id) == -1) {
          this.data.errword.push(this.data.worldsEn[idx].id);
        }
      }
      if (this.data.allword.indexOf(this.data.worldsEn[idx].id) == -1) {
        this.data.allword.push(this.data.worldsEn[idx].id);
      }

    }
  },
  replay: function() {
    this.setData({
      jbDis: 'flex',
      gfDis: 'none',
	  reply:true
    })
  },
  rePass: function() { //进入下一关
    // clearInterval(this.data.timer);
	this.cleartime()
    if (this.data.gameSecond2 > 0) {
      this.daojishi();
    }
  }
})